from pandas import read_csv
from numpy import NaN
from urllib import parse

import requests


def doi2bib(doi):
    """
    Return a bibTeX string of metadata for a given DOI.
    """

    url = "http://dx.doi.org/" + doi

    headers = {"accept": "application/x-bibtex"}
    r = requests.get(url, headers=headers)

    return r.text


ref_df = read_csv("./reference.csv", header=0)

# Parse the doi to the real doi
with open("./reference.bib", "w") as f:
    for row in ref_df[ref_df.year.isin(["2015", "2016", "2017"])].itertuples():
        if row.doi is not NaN:
            bibtex = doi2bib(parse.unquote(row.doi))
            if len(bibtex) > 1:
                print(str(row.number) + ": ", row.title)
                bibtex_num = "@article{" + f"ref{row.number},\n" + \
                    ",\n".join(bibtex.split(",\n")[1:]) + "\n\n"
                f.write(bibtex_num)
